// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var Application = Class.create();

Object.extend(Application, {
  getCookie: function(name) {
    var value = null;
    if (typeof(document.cookie) != 'undefined') {
      $A(document.cookie.split(';')).each(function(v) {
        var kv = v.split('=');
        if (name.toLowerCase() == kv[0].toLowerCase().strip()) {
          value = kv[1].strip();
          throw $break;
        }
      });
    }
    return value;
  },

  setCookie: function(name, value, days) {
    if (typeof(document.cookie) == 'undefined') return;
    // Set expiration
    var expires = new Date();
    if (days) {
      expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
    }
    else {
      expires.setMonth(expires.getMonth() + 12);
    }
    var encode = encodeURIComponent || escape;
    value = encode(name) + '=' + encode(value);
    value += '; expires=' + expires.toUTCString();
    value += '; path=/';
    document.cookie = value;
  },

  getName: function() {
    return Utf8.decode(unescape(Application.getCookie('name')));
  },

  getEmail: function() {
    return Utf8.decode(unescape(Application.getCookie('email')));
  },
  
  toggle: function(el) {
    if ($(el)) {
      target = $(el).up('.togglable');
      if (target) {
        if (target.hasClassName('toggle_on')) {
          target.removeClassName('toggle_on');
          target.addClassName('toggle_off');
        }
        else {
          target.removeClassName('toggle_off');
          target.addClassName('toggle_on');
        }
      }
    }
  }
});


// from http://www.webtoolkit.info/javascript-utf8.html
var Utf8 = {
  decode: function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;
 
    while ( i < utftext.length ) {
      c = utftext.charCodeAt(i);
      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      }
      else if((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i+1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      }
      else {
        c2 = utftext.charCodeAt(i+1);
        c3 = utftext.charCodeAt(i+2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }
 
    }
    return string;
  }
};
